/**
 * @Description: 推荐组件
 * 调用后端接口，向用户推荐书籍
 * @author zhaojiuyi
 * @date 2023/4/16
 */
import {FC, useEffect, useState} from "react";
import {
    BookConfig,
    getBookHotList,
    getRecommendBooks,
    getRecommendBooksFirstLogin,
    getUserIsFirstLogin,
    UserProfile
} from "@/apis/recommend";
import {ApiConstants} from "@/apis/constants";
import {errorMessage} from "@/common/components/Message";
import {Book} from "./Book";
import {Spin} from "antd";
import {SelectLike} from "@/common/components/SelectLike";

export const RecommendBooks: FC = (props) => {
    const size = 20 // 请求的数据长度
    const [bookList, setBookList] = useState<BookConfig[]>([])
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false)

    const getLikeData = (likeDate:UserProfile) => {
        setIsModalOpen(false)
        getRecommendBooksFirstLogin(size,likeDate).then(result => {
            console.log(result)
            setBookList(result.data)
        })
    }


    useEffect(() => {
        console.log("recommend mounted")

        /* 检测用户是否首次进入 */
        async function testIsFirstLogin(): Promise<void>{
            const {data} = await getUserIsFirstLogin()
            if(data){
                setIsModalOpen(true)
            }else{
                getData().then((result: BookConfig[]) => {
                    setBookList(result)
                })
            }
        }


        async function getData(): Promise<BookConfig[]> {
            const {code, data, msg} = await getRecommendBooks(size)
            if (code !== ApiConstants.SUCCESS) return errorMessage(msg)
            if (!data.length) {
                const {data} = await getBookHotList(size)
                return data
            }
            return data
        }

        testIsFirstLogin().then()


    }, [])
    return (
        <>
            <SelectLike open={isModalOpen} getLikeData={getLikeData}/>
            <Spin spinning={!bookList.length}>
                <h2>推荐</h2>
                <div className="recommend">
                    {
                        bookList.map(item => {
                            // console.log(item.id)
                            return <Book key={item.id} {...item}/>
                        })
                    }
                </div>
            </Spin>
        </>
    )

}
